package com.supplychainapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.joindata.inf.common.basic.exceptions.ServiceException;
import com.supplychainapi.common.enums.ExceptionMessage;
import com.supplychainapi.dao.prod.ScmTbpurchaseMapper;
import com.supplychainapi.dao.prod.ScmTbpurchasedtlMapper;
import com.supplychainapi.domain.HQPurchaseParam;
import com.supplychainapi.domain.HeadquartersPurchase;
import com.supplychainapi.domain.LoginCache;
import com.supplychainapi.domain.Tbpurchase;
import com.supplychainapi.model.ScmTbpurchase;
import com.supplychainapi.model.ScmTbpurchasedtl;
import com.supplychainapi.param.PurchaseParam;
import com.supplychainapi.service.IScmTbpurchaseService;
import com.supplychainapi.service.TbSeqNoService;
import com.supplychainapi.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *
 * 采购订单
 * @author:xiezhiwei
 * @email:xiezhiwei@niwodai.net
 * @date:2017-11-27
 *
 */
@Service
public class ScmTbpurchaseServiceImpl implements IScmTbpurchaseService {

	private Logger logger = LogManager.getLogger(ScmTbpurchaseServiceImpl.class);

	@Autowired
	private ScmTbpurchaseMapper purchaseMapper;

	@Autowired
	private ScmTbpurchasedtlMapper purchasedtlMapper;


	@Autowired
	TbSeqNoService seqNoService;

	@Override
	public List<ScmTbpurchase> getPurchaseListInfo(PurchaseParam purchaseParam) throws ServiceException {
		if (purchaseParam.getPage() != null) {
			// page = (page - 1) * pageSize;
			purchaseParam.setPage((purchaseParam.getPage() - 1) * purchaseParam.getPageSize());
		} else {
			//page = 0;
			purchaseParam.setPage(0);
		}
		List<ScmTbpurchase> purchaseList = purchaseMapper.getPurchaseListInfo(purchaseParam);
		return purchaseList;
	}

	@Override
	public int save(ScmTbpurchase model) throws ServiceException {
		return purchaseMapper.insertSelective(model);

	}

	@Override
	public int delete(ScmTbpurchase model) throws ServiceException {
		return purchaseMapper.deleteByPrimaryKey(model);

	}

	@Override
	public List<ScmTbpurchase> search(String shopGuid, Integer pageNum, Integer pageSize, String keyWords, String fiBillStatus) throws ServiceException {
		PageHelper.startPage(pageNum, pageSize);
		Example example = new Example(ScmTbpurchase.class);
		Example.Criteria criteria = example.createCriteria().andEqualTo("fsshopguid", shopGuid);
		if (StringUtils.isNotBlank(fiBillStatus)) {
			criteria.andEqualTo("fibillstatus", fiBillStatus);
		}
		if (StringUtils.isNotBlank(keyWords)) {//单号 供应商  订单备注模糊搜索
			criteria.orLike("fsPurchaseNo", "%".concat(keyWords).concat("%"));
			criteria.orLike("fsSupplierName", "%".concat(keyWords).concat("%"));
			criteria.orLike("fsNote", "%".concat(keyWords).concat("%"));
		}
		return purchaseMapper.selectByExample(example);
	}

	@Override
	public ScmTbpurchase selectById(String fsPurchaseGUID) throws ServiceException {
		if (StringUtils.isBlank(fsPurchaseGUID)) {
			throw ExceptionMessage.missing_param.getServiceException();
		}
		return purchaseMapper.selectByPrimaryKey(fsPurchaseGUID);
	}

	@Override
	public int update(Tbpurchase model) throws ServiceException {
		if (null == model) {
			throw ExceptionMessage.missing_param.getServiceException();
		}
		ScmTbpurchase tbpurchase = new ScmTbpurchase();
		BeanUtils.copyProperties(model, tbpurchase);
		return purchaseMapper.updateByPrimaryKeySelective(tbpurchase);
	}

	@Override
	@Transactional
	public int addHeadquarters(ScmTbpurchase purchase) throws ServiceException {
		logger.info("purchase={}",JSON.toJSON(purchase));
		purchase.setFscreatetime(new Date());
		purchase.setFsupdatetime(new Date());
		purchase.setFspurchaseno(seqNoService.getOrderNo("1105", "scm_tbpurchase", purchase.getFsshopguid()));
		purchase.setFspurchaseguid(DateUtils.getNowTimestamp());//当前时间戳

		BigDecimal fdPurchaseTotAmt = purchase.getFdpurchasemoneyamt().add(purchase.getFdpurchasetaxamt()); //采购价税合计;采购金额+采购税额
		purchase.setFdpurchasetotamt(fdPurchaseTotAmt);
		int count = purchaseMapper.insertSelective(purchase);
		if (count > 0) {
			List<ScmTbpurchasedtl> purchasedtlList = purchase.getPurchasedtlList();
			if (purchasedtlList != null && purchasedtlList.size() > 0) {
				for (ScmTbpurchasedtl scmTbpurchasedtl : purchasedtlList) {
					String fspguid = scmTbpurchasedtl.getFspguid();
					if (StringUtils.isNotBlank(fspguid)) {//平台
						scmTbpurchasedtl.setFidataflag((short) 2);
					} else {
						scmTbpurchasedtl.setFidataflag((short) 1);
					}
					scmTbpurchasedtl.setFspurchaseguid(purchase.getFspurchaseguid());
					scmTbpurchasedtl.setFspurchaseno(purchase.getFspurchaseno());
					//setScale(2, RoundingMode.HALF_UP)
					BigDecimal fdtaxrate = scmTbpurchasedtl.getFdtaxrate().divide(new BigDecimal(100));//税率
					logger.info("税率 -->fdtaxrate={}", fdtaxrate);

					BigDecimal fdTaxPrice = scmTbpurchasedtl.getFdprice().multiply(fdtaxrate).setScale(2,RoundingMode.HALF_UP);//含税单价;单价*税率*0.01 .multiply(new BigDecimal(0.01))
					logger.info("含税单价 -->fdTaxPrice={}", fdTaxPrice);
					scmTbpurchasedtl.setFdtaxprice(fdTaxPrice);

					BigDecimal fdMoney = scmTbpurchasedtl.getFdqty().multiply(scmTbpurchasedtl.getFdprice());//金额
					logger.info("金额=数量x单价 fdMoney={}", fdMoney);
					scmTbpurchasedtl.setFdmoney(fdMoney);//金额;=数量*单价

					BigDecimal fdTax = scmTbpurchasedtl.getFdmoney().multiply(fdtaxrate).setScale(2,RoundingMode.HALF_UP);//税额;=金额*税率*0.01 .multiply(new BigDecimal(0.01))
					logger.info("税额 -->fdTax={}", fdTax);
					scmTbpurchasedtl.setFdtax(fdTax);

					BigDecimal fdTotal = scmTbpurchasedtl.getFdmoney().add(fdTax);//价税合计;=金额+税额
					logger.info("价税合计-->fdTotal={}", fdTotal);
					scmTbpurchasedtl.setFdtotal(fdTotal);

					scmTbpurchasedtl.setFsshopguid(purchase.getFsshopguid());
					scmTbpurchasedtl.setFscreateuserid(purchase.getFscreateuserid());
					scmTbpurchasedtl.setFscreateusername(purchase.getFscreateusername());
					scmTbpurchasedtl.setFsupdateuserid(purchase.getFscreateuserid());
					scmTbpurchasedtl.setFsupdateusername(purchase.getFsupdateusername());
					scmTbpurchasedtl.setFscreatetime(new Date());
					scmTbpurchasedtl.setFsupdatetime(new Date());
					purchasedtlMapper.insertSelective(scmTbpurchasedtl);
				}
			}
		}
		return count;
	}

	@Override
	@Transactional
	public int addHeadquarters(LoginCache loginCache, HQPurchaseParam purchaseParam) throws ServiceException {
		logger.info("purchase={}",JSON.toJSON(purchaseParam));
		List<HeadquartersPurchase> HeadquartersPurchaseList = purchaseParam.getHeadquartersPurchase();
		int count=0;
		if(HeadquartersPurchaseList!=null && HeadquartersPurchaseList.size()>0){
			for (HeadquartersPurchase headquartersPurchase : HeadquartersPurchaseList) {
		        ScmTbpurchase purchase = new ScmTbpurchase();
		        BeanUtils.copyProperties(headquartersPurchase, purchase);
		        
		        purchase.setFsshopname(loginCache.getFsShopName());
		        purchase.setFsshopguid(loginCache.getFsShopGUID());
	        	purchase.setFscreateuserid(loginCache.getFsUserId());
	        	purchase.setFscreateusername(loginCache.getFsUserName());
	        	purchase.setFsupdateuserid(loginCache.getFsUserId());
	        	purchase.setFsupdateusername(loginCache.getFsUserName());
	        	
	        	purchase.setFscreatetime(new Date());
	    		purchase.setFsupdatetime(new Date());
	    		purchase.setFspurchaseno(seqNoService.getOrderNo("1105", "scm_tbpurchase", purchase.getFsshopguid()));
	    		purchase.setFspurchaseguid(DateUtils.getNowTimestamp());//当前时间戳
	
	    		BigDecimal fdPurchaseTotAmt = purchase.getFdpurchasemoneyamt().add(purchase.getFdpurchasetaxamt()); //采购价税合计;采购金额+采购税额
	    		purchase.setFdpurchasetotamt(fdPurchaseTotAmt);
	    		count = purchaseMapper.insertSelective(purchase);
	    		if (count > 0) {
	    			List<ScmTbpurchasedtl> purchasedtlList = purchase.getPurchasedtlList();
	    			if (purchasedtlList != null && purchasedtlList.size() > 0) {
	    				for (ScmTbpurchasedtl scmTbpurchasedtl : purchasedtlList) {
	    					String fspguid = scmTbpurchasedtl.getFspguid();
	    					if (StringUtils.isNotBlank(fspguid)) {//平台
	    						scmTbpurchasedtl.setFidataflag((short) 2);
	    					} else {
	    						scmTbpurchasedtl.setFidataflag((short) 1);
	    					}
	    					scmTbpurchasedtl.setFspurchaseguid(purchase.getFspurchaseguid());
	    					scmTbpurchasedtl.setFspurchaseno(purchase.getFspurchaseno());
	    					//setScale(2, RoundingMode.HALF_UP)
	    					BigDecimal fdtaxrate = scmTbpurchasedtl.getFdtaxrate().divide(new BigDecimal(100));//税率
	    					logger.info("税率 -->fdtaxrate={}", fdtaxrate);
	
	    					BigDecimal fdTaxPrice = scmTbpurchasedtl.getFdprice().multiply(fdtaxrate).setScale(2,RoundingMode.HALF_UP);//含税单价;单价*税率*0.01 .multiply(new BigDecimal(0.01))
	    					logger.info("含税单价 -->fdTaxPrice={}", fdTaxPrice);
	    					scmTbpurchasedtl.setFdtaxprice(fdTaxPrice);
	
	    					BigDecimal fdMoney = scmTbpurchasedtl.getFdqty().multiply(scmTbpurchasedtl.getFdprice());//金额
	    					logger.info("金额=数量x单价 fdMoney={}", fdMoney);
	    					scmTbpurchasedtl.setFdmoney(fdMoney);//金额;=数量*单价
	
	    					BigDecimal fdTax = scmTbpurchasedtl.getFdmoney().multiply(fdtaxrate).setScale(2,RoundingMode.HALF_UP);//税额;=金额*税率*0.01 .multiply(new BigDecimal(0.01))
	    					logger.info("税额 -->fdTax={}", fdTax);
	    					scmTbpurchasedtl.setFdtax(fdTax);
	
	    					BigDecimal fdTotal = scmTbpurchasedtl.getFdmoney().add(fdTax);//价税合计;=金额+税额
	    					logger.info("价税合计-->fdTotal={}", fdTotal);
	    					scmTbpurchasedtl.setFdtotal(fdTotal);
	
	    					scmTbpurchasedtl.setFsshopguid(purchase.getFsshopguid());
	    					scmTbpurchasedtl.setFscreateuserid(purchase.getFscreateuserid());
	    					scmTbpurchasedtl.setFscreateusername(purchase.getFscreateusername());
	    					scmTbpurchasedtl.setFsupdateuserid(purchase.getFscreateuserid());
	    					scmTbpurchasedtl.setFsupdateusername(purchase.getFsupdateusername());
	    					scmTbpurchasedtl.setFscreatetime(new Date());
	    					scmTbpurchasedtl.setFsupdatetime(new Date());
	    					purchasedtlMapper.insertSelective(scmTbpurchasedtl);
	    				}
	    			}
	    		}
			}
		}
		return count;
	}
}
